package com.prinxchengshan.reportbase.service;

import com.prinxchengshan.reportbase.Utils.ExcelUtil;
import com.prinxchengshan.reportbase.mapper.CreditExceedingMapper;
import com.prinxchengshan.reportbase.pojo.CreditExceeding;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.io.FileOutputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@Service
public class CreditExceedingService {

    @Autowired
    private CreditExceedingMapper ceMapper;

    @Autowired(required = false)
    private JavaMailSender mailSender;


    @Value("${spring.mail.from}") // 从application.yml配置文件中获取
    private String from; // 发送发邮箱地址

    // 每小时发送一次邮件（邮件中）
    @Scheduled(cron = "0 0 0/1 * * ?")
    // @Scheduled(cron = "0 10 17 * * ?")
    public void sendEmailHour(){
        System.out.println("CreditExceedingService.sendEmailHour");
        //  获取信用超额的数据
        List<CreditExceeding> creditExceedings = ceMapper.callProcedure();

        if(creditExceedings.isEmpty()){
            return;
        }

        String[] titles = new String[]{"客户号","信用用超金额"};

        String fileName = "信用超额数据.xlsx";

        // 将信用超额的数据写入到Excel中
        writeToExcel(creditExceedings,titles,fileName);

        //  设置收件人
        InternetAddress[] toList = setReceiver();

        //  发送邮件
        // 测试单个附件邮件发送
        String title = "CRM信用超额数据";
        String content = "CRM信用超额数据";
        File file = new File("src\\main\\resources\\"+fileName);
        sendEmail(toList,title,content,file);


    }

    // 发送邮件
    private void sendEmail(InternetAddress[] toList , String subject , String content , File file) {
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper helper = null;
        try{
            helper  = new MimeMessageHelper(mimeMessage,true);
            helper.setFrom(from); // 设置发送方
            helper.setTo(toList); // 设置接收方
            helper.setSubject(subject); // 设置邮件主题
            helper.setText(content); // 设置邮件内容
            helper.addAttachment(file.getName(), file); // 单个附件
            mailSender.send(mimeMessage);
        }catch (Exception e){
            e.printStackTrace();
        }


    }

    // 设置收件人
    private InternetAddress[] setReceiver() {

        InternetAddress[]  toList = new InternetAddress[0];


        String[] toStrings = ExcelUtil.ExcelToArray("CRM信用超额发送名单.xlsx");

        for (int i = 0; i < toStrings.length; i++) {
            toList = addToList(toList,toStrings[i]);
        }


        return toList;



    }

    private InternetAddress[] addToList(InternetAddress[] toList, String toString) {
        InternetAddress to = null;
        try{
            to = new InternetAddress(toString);
        }catch ( Exception e){
            System.out.println(e);
        }


        // 将数组转换为ArrayList
        ArrayList<InternetAddress> arrayList = new ArrayList<>(Arrays.asList(toList));

        // 向ArrayList中添加新元素
        arrayList.add(to);

        // 将ArrayList转换回数组
        InternetAddress[] newArray = arrayList.toArray(new InternetAddress[0]);

        return newArray;
    }

    // 将信用超额的数据写入到Excel中
    public void writeToExcel(List<CreditExceeding> creditExceedings, String[] titles,String fileName){
        XSSFWorkbook xssfWorkbook=new XSSFWorkbook();
        XSSFSheet xssfSheet=xssfWorkbook.createSheet("CRM用超信用额度");
        Row row2=xssfSheet.createRow(0);
        for (int i=0;i< titles.length;i++){
            row2.createCell(i).setCellValue(titles[i]);
        }


        int rowIndex = 1;
        for (CreditExceeding creditExceeding : creditExceedings) {
            final int[] colunIndex = {0};
            XSSFRow row1 = xssfSheet.createRow(rowIndex++);

            try{
                Map describeMap = BeanUtils.describe(creditExceeding);
                describeMap.remove("class");

                describeMap.forEach(
                        (k, v) -> {
                            row1.createCell(colunIndex[0]++).setCellValue( ((String) v) );
                        }
                );
            }catch (Exception e){
                throw new RuntimeException(e);
            }



        }

        String local_path = System.getProperty("user.dir");
        //获取当前用户的当前工作目录
        String path = local_path+"\\src\\main\\resources\\" + fileName;
        //添加上文件的路径，组成文件的绝对路径
        File file=new File(path);
        try{
            FileOutputStream fileOutputStream=new FileOutputStream(file);
            xssfWorkbook.write(fileOutputStream);
            //通过流的方式写入到文件中中
            fileOutputStream.close();
            //使用完成之后要记得关闭这个流
        }catch (Exception E){
            System.out.println("写入Excel失败");
        }


    }
}
